// Script for compiling build behavior. It is built in the build plug-in and cannot be modified currently.
import { getHvigorNode } from '@ohos/hvigor';
import { basename, resolve } from "path";
import { InjectUtil } from "../../../../src/utils/inject-util.js";
import { BuildDirConst } from "../../../../src/const/build-directory-const.js";

const project = require('@ohos/hvigor').getHvigorNode(__filename);
const ohosPlugin = require('@ohos/hvigor-ohos-plugin').hapTasks(project);

const fs = require('fs-extra');
const path = require('path');
const execa = require('execa');

project.task(function () {
  console.log('This is a entry1 task');
}, 'hello');


const onlineSignTask = project.task(() => {
  const userName = process.env.W3_ACCOUNT;
  const password = process.env.W3_PASS_WORD;
  const projectPath = project.getNodeDir();
  const projectName = project.getName();

  const inputFile = path.resolve(projectPath, `build/default/outputs/default/${projectName}-default-unsigned.hap`);
  console.log(inputFile);

  const rootProject = project.getProject();
  const rootProjectBuildDir = resolve(InjectUtil.getBuildCacheParentDir(rootProject.getNodeDir(), basename(rootProject.getNodeDir())),
    BuildDirConst.BUILD_ROOT);
  if (!fs.existsSync(rootProjectBuildDir)) {
    fs.mkdirSync(rootProjectBuildDir, { recursive: true });
  }
  const outputFile = path.resolve(rootProjectBuildDir, `${projectName}-onlingeSigned.hap`);
  console.log(outputFile);

  const command = [
    '-jar',
    'D:\\hapsigntoolv2.jar',
    'sign',
    '-mode',
    'remote',
    '-server',
    'http://inner.rnd-signserver.huawei.com/sign',
    '-username',
    userName,
    '-password',
    password,
    '-profile',
    'D:\\study\\testcase\\onlinesign\\onlinesign\\1640749245761debug.p7b',
    '-signAlg',
    'SHA256withECDSA',
    '-privatekey',
    'HOS Application Provision Debug',
    '-inputFile',
    inputFile,
    '-outputFile',
    outputFile
  ];
  console.log(command);
  const result = execa.sync('java', command);
}, {
  name: 'onlineSign',
  description: 'Use huawei pki sign hap.',
  isEnabled: true
}).dependsOn('default@PackageHap');

if (onlineSignTask.getEnabled()){
  project.getTaskByName('default@SignHap').setEnabled(false);
}

project.getTaskByName('assembleHap').dependsOn('onlineSign');

// assembleHap->SignHap->PackageHap
// SignHap->disabled
// assembleHap->onlineSign->PackageHap

module.exports = {
  ohos: ohosPlugin
};
